package com.android.kotlin.base

import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.android.kotlin.R
import com.android.kotlin.util.AppManager
import com.arms.mvvm.view.statusbar.barlibrary.ImmersionBar
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import io.reactivex.disposables.Disposable
import org.jetbrains.anko.toast

/**
 * author：  HyZhan
 * created： 2018/10/10 10:47
 * desc：    TODO
 */
abstract class BaseActivity : AppCompatActivity() {

    private var pressTime: Long = 0

    protected var disposable: Disposable? = null

    val mImmersionBar:ImmersionBar by lazy {
        ImmersionBar.with(this)
    }

    protected val loadService: LoadService<*> by lazy {
        LoadSir.getDefault().register(getLoadSirView()) {
            reLoad()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        AppManager.instance.addActivity(this)
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar()
        }
        initView()
        initData()
    }

    abstract fun getLayoutId(): Int

    abstract fun getLoadSirView():Any

    open fun initView() {}
    open fun initData() {}

    // 重新加载
    open fun reLoad() {
        initData()
    }

    // 设置 防错误操作 退出 activity
    override fun onBackPressed() {
        val time = System.currentTimeMillis()
        if (time - pressTime > 2000) {
            toast(getString(R.string.exit_app_tips))
            pressTime = time
        } else {
            AppManager.instance.exitApp(this)
        }
    }



    override fun onDestroy() {
        super.onDestroy()
        AppManager.instance.removeActivity(this)
        // 取消订阅
        disposable?.dispose()
    }


    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    open fun isImmersionBarEnabled(): Boolean {
        return true
    }

    /**
     * Init immersion bar.
     */
    open fun initImmersionBar() {
        mImmersionBar.init()
        initBarWhite(this)
    }


    /**
     * Init bar white.
     *
     * @param activity
     * the activity
     */
    fun initBarWhite(activity: Activity?) {
        if (activity == null || activity.isFinishing) {
            return
        }
        mImmersionBar
            .statusBarDarkFont(true)
            .init()
//        mImmersionBar.statusBarDarkFont(true, 0.5f)
//            .init()
    }

    /**
     * Init bar blue.
     *
     * @param activity
     * the activity
     */
    fun initBarBluekeyboard(activity: Activity?) {
        if (activity == null || activity.isFinishing) {
            return
        }
        mImmersionBar.statusBarDarkFont(false, 0.3f)
            .keyboardEnable(true)
            .init()

    }


}